/**
 * 朋知云学平台工具函数库
 * 包含通用功能和工具函数，供各个页面使用
 */

// 初始化通知系统
function initNotifications() {
    // 创建通知容器
    if (!document.querySelector('.notification-container')) {
        const container = document.createElement('div');
        container.className = 'notification-container';
        document.body.appendChild(container);
    }
}

/**
 * 显示通知
 * @param {string} message - 通知消息
 * @param {string} type - 通知类型 (success, error, warning, info)
 * @param {number} duration - 显示时长(毫秒)
 */
function showNotification(message, type = 'info', duration = 3000) {
    // 确保通知容器存在
    initNotifications();
    
    const container = document.querySelector('.notification-container');
    
    // 创建通知元素
    const notification = document.createElement('div');
    notification.className = `notification notification-${type}`;
    
    // 设置通知内容
    notification.innerHTML = `
        <div class="notification-content">${message}</div>
        <button class="notification-close">&times;</button>
    `;
    
    // 添加到容器
    container.appendChild(notification);
    
    // 显示通知
    setTimeout(() => {
        notification.classList.add('show');
    }, 10);
    
    // 关闭按钮事件
    const closeBtn = notification.querySelector('.notification-close');
    closeBtn.addEventListener('click', () => {
        closeNotification(notification);
    });
    
    // 自动关闭
    if (duration > 0) {
        setTimeout(() => {
            closeNotification(notification);
        }, duration);
    }
}

/**
 * 关闭通知
 * @param {HTMLElement} notification - 通知元素
 */
function closeNotification(notification) {
    notification.classList.remove('show');
    
    // 动画结束后移除元素
    setTimeout(() => {
        if (notification.parentElement) {
            notification.parentElement.removeChild(notification);
        }
    }, 300);
}

/**
 * 创建模态框
 * @param {Object} options - 模态框配置
 * @returns {Object} - 模态框对象
 */
function createModal(options = {}) {
    const defaults = {
        title: '提示',
        content: '',
        confirmText: '确定',
        cancelText: '取消',
        showCancel: true,
        onConfirm: null,
        onCancel: null,
        onClose: null
    };
    
    const settings = { ...defaults, ...options };
    
    // 创建模态框元素
    const modal = document.createElement('div');
    modal.className = 'modal';
    
    // 设置模态框内容
    modal.innerHTML = `
        <div class="modal-content">
            <div class="modal-header">
                <h3 class="modal-title">${settings.title}</h3>
                <button class="modal-close">&times;</button>
            </div>
            <div class="modal-body">${settings.content}</div>
            <div class="modal-footer">
                ${settings.showCancel ? `<button class="btn btn-secondary modal-cancel">${settings.cancelText}</button>` : ''}
                <button class="btn btn-primary modal-confirm">${settings.confirmText}</button>
            </div>
        </div>
    `;
    
    // 添加到文档
    document.body.appendChild(modal);
    
    // 显示模态框
    setTimeout(() => {
        modal.classList.add('show');
    }, 10);
    
    // 关闭模态框函数
    const closeModal = () => {
        modal.classList.remove('show');
        setTimeout(() => {
            if (modal.parentElement) {
                modal.parentElement.removeChild(modal);
            }
        }, 300);
    };
    
    // 绑定事件
    const closeBtn = modal.querySelector('.modal-close');
    closeBtn.addEventListener('click', () => {
        if (typeof settings.onClose === 'function') {
            settings.onClose();
        }
        closeModal();
    });
    
    const confirmBtn = modal.querySelector('.modal-confirm');
    confirmBtn.addEventListener('click', () => {
        if (typeof settings.onConfirm === 'function') {
            settings.onConfirm();
        }
        closeModal();
    });
    
    if (settings.showCancel) {
        const cancelBtn = modal.querySelector('.modal-cancel');
        cancelBtn.addEventListener('click', () => {
            if (typeof settings.onCancel === 'function') {
                settings.onCancel();
            }
            closeModal();
        });
    }
    
    // 返回模态框对象
    return {
        element: modal,
        close: closeModal
    };
}

/**
 * 显示确认对话框
 * @param {string} message - 提示消息
 * @param {Function} onConfirm - 确认回调
 * @param {Function} onCancel - 取消回调
 */
function showConfirm(message, onConfirm, onCancel) {
    createModal({
        title: '确认',
        content: message,
        onConfirm,
        onCancel
    });
}

/**
 * 显示提示对话框
 * @param {string} message - 提示消息
 * @param {Function} onClose - 关闭回调
 */
function showAlert(message, onClose) {
    createModal({
        title: '提示',
        content: message,
        showCancel: false,
        onConfirm: onClose,
        onClose
    });
}

/**
 * 关闭模态框
 */
function closeModal() {
    const modal = document.querySelector('.modal');
    if (modal) {
        modal.classList.remove('show');
        setTimeout(() => {
            if (modal.parentElement) {
                modal.parentElement.removeChild(modal);
            }
        }, 300);
    }
}

/**
 * 更新下拉菜单选项
 * @param {HTMLElement} row - 表格行元素
 * @param {string} status - 状态文本
 */
function updateDropdownMenu(row, status) {
    const dropdown = row.querySelector('.dropdown-menu');
    if (!dropdown) return;
    
    // 根据状态更新下拉菜单选项
    if (status === '已发布') {
        dropdown.innerHTML = `
            <a href="#" class="dropdown-item">
                <i class="bi bi-x-circle"></i> 关闭需求
            </a>
            <a href="#" class="dropdown-item">
                <i class="bi bi-arrow-up-circle"></i> 置顶
            </a>
            <a href="#" class="dropdown-item text-danger">
                <i class="bi bi-trash"></i> 删除
            </a>
        `;
    } else if (status === '待审核') {
        dropdown.innerHTML = `
            <a href="#" class="dropdown-item">
                <i class="bi bi-check-circle"></i> 审核通过
            </a>
            <a href="#" class="dropdown-item">
                <i class="bi bi-x-circle"></i> 拒绝
            </a>
            <a href="#" class="dropdown-item text-danger">
                <i class="bi bi-trash"></i> 删除
            </a>
        `;
    } else if (status === '已关闭') {
        dropdown.innerHTML = `
            <a href="#" class="dropdown-item">
                <i class="bi bi-arrow-counterclockwise"></i> 重新开放
            </a>
            <a href="#" class="dropdown-item text-danger">
                <i class="bi bi-trash"></i> 删除
            </a>
        `;
    }
}

/**
 * 绑定需求操作事件
 */
function bindDemandActions() {
    // 下拉菜单项点击事件
    document.querySelectorAll('.dropdown-menu a').forEach(item => {
        item.addEventListener('click', function(e) {
            e.preventDefault();
            
            const action = this.textContent.trim();
            const row = this.closest('tr');
            const demandTitle = row.querySelector('.demand-title').textContent;
            
            switch (action) {
                case '审核通过':
                    approveDemand(demandTitle, row);
                    break;
                case '拒绝':
                    rejectDemand(demandTitle, row);
                    break;
                case '置顶':
                    pinDemand(demandTitle, row);
                    break;
                case '重新开放':
                    reopenDemand(demandTitle, row);
                    break;
                case '关闭需求':
                    closeDemand(demandTitle, row);
                    break;
                case '删除':
                    deleteDemand(demandTitle, row);
                    break;
            }
            
            // 关闭下拉菜单
            const dropdown = this.closest('.dropdown-menu');
            if (dropdown) {
                dropdown.classList.remove('show');
            }
        });
    });
    
    // 查看详情按钮事件
    document.querySelectorAll('.btn-icon[title="查看详情"]').forEach(btn => {
        btn.addEventListener('click', function() {
            const row = this.closest('tr');
            const demandTitle = row.querySelector('.demand-title').textContent;
            showDemandDetails(demandTitle, row);
        });
    });
    
    // 编辑按钮事件
    document.querySelectorAll('.btn-icon[title="编辑"]').forEach(btn => {
        btn.addEventListener('click', function() {
            const row = this.closest('tr');
            const demandTitle = row.querySelector('.demand-title').textContent;
            editDemand(demandTitle, row);
        });
    });
}

/**
 * 关闭需求
 * @param {string} demandTitle - 需求标题
 * @param {HTMLElement} row - 表格行元素
 */
function closeDemand(demandTitle, row) {
    showConfirm(
        `确定要关闭需求 ${demandTitle} 吗？`,
        function() {
            // 更新状态标识
            const statusBadge = row.querySelector('.status-badge');
            statusBadge.className = 'status-badge status-closed';
            statusBadge.textContent = '已关闭';
            
            // 更新下拉菜单选项
            updateDropdownMenu(row, '已关闭');
            
            // 重新绑定事件
            bindDemandActions();
            
            // 显示成功通知
            showNotification(`需求 ${demandTitle} 已关闭`, 'success');
        }
    );
}

// 导出工具函数
window.utils = {
    showNotification,
    closeNotification,
    createModal,
    showConfirm,
    showAlert,
    closeModal,
    updateDropdownMenu,
    bindDemandActions
};